// 威威猫系列故事——打地鼠
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#define Max 55
using namespace std;

int a[Max][Max];
int dp[Max][Max];

int main(void)
{
    int n, k;
    while (scanf("%d%d", &n, &k) != EOF)
    {
        for (int i = 1; i <= n; i++)
            for (int j = 1; j <= k; j++)
                scanf("%d", &a[i][j]);

        for (int i = 1; i <= k; i++)
            dp[1][i] = 0;

        //核心
        for (int t = 2; t <= n; t++)
            for (int j = 1; j <= k; j++)
                for (int x = 1; x <= k; x++)
                    if (x == 1)
                        dp[t][j] = dp[t - 1][x] + abs(a[t - 1][x] - a[t][j]);
                    else
                        dp[t][j] = min(dp[t][j], dp[t - 1][x] + abs(a[t - 1][x] - a[t][j]));

        int min = dp[n][1];
        for (int i = 2; i <= k; i++)
            if (min > dp[n][i])
                min = dp[n][i];

        printf("%d\n", min);
    }

    fclose(stdin);
    return 0;
}